﻿<%@ WebHandler Language="VB" Class="ContainerStepCheckHandler" %>

Imports System
Imports System.Web
Imports BusinessRule.DTO
Imports System.Web.SessionState
Imports DatabaseAccess.DBUtility
Imports System.Data.OracleClient
Imports System.Data
Imports System.Linq
Imports System.Collections
Imports Newtonsoft.Json
Imports BusinessRule.Business
Imports BusinessRule.IBusiness
Imports BusinessRule.BusinessFactory
Imports BusinessRule.Common

'Description: 流水卡检验、首件二检处理程序
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20220824
'Rewriter:
'Rewrite Date:

Public Class ContainerStepCheckHandler : Implements IHttpHandler, IRequiresSessionState
    Dim m_UserInfo As New CurrentUserInfo
    Private m_Commission As uLMSCommissioningIBusiness = uMESBusinessFactory.instance.GetuLMSCommissioning
    Private m_ContainerObj As uLMSContainerIBusiness = uMESBusinessFactory.instance.GetuLMSContainerObject()
    Private m_ConCurrentinfo As uLMSContainercurrentinfoIBusiness = uMESBusinessFactory.instance.GetuLMSContainerCurrentInfoObject()
    Private checkBusiness As uLMSCheckIBusiness = uMESBusinessFactory.instance.GetuLMSCheckObject
    Private m_Common As uLMSCommonIBusiness = uMESBusinessFactory.instance.GetuLMSCommonObject
    Private m_ReportBusiness As uLMSWorkReportIBusiness = uMESBusinessFactory.instance.GetuLMSWorkReportObject
    Private oIBusiness As uMESContainerInfoPrintIBusiness = uMESBusinessFactory.instance.GetContainerInfoPrintObject("LY_JX")
    Private m_DispatchObj As uLMSDispatchIBusiness = uMESBusinessFactory.instance.GetuLMSDispatchObject
    Private strProductName As String
    Public htmlstr As String
    Public strHtmlTable As String
    Public strContainerName As String
    Public strMfgordername As String
    Private strContainerID As String
    Private isselfmfg As Boolean
    Private partCharacterType As String
    Private bomPersonMerge As String 'add:Wangjh 20180607 配套表人员是否合并
    Private startDate As String 'add:Wangjh 20180524
    Private strTechniqueEmp As String
    Private strPlanName As String
    Private wfFactoryName As String
    Private stepWorkReportDt As DataTable
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim result = New uMESProcessResult()
        Try
            Dim action As String = context.Request("action").ToString()
            m_UserInfo = context.Session("CurrentUserInfo")
            If IsDBNull(m_UserInfo) Then
                result.Result = False
                result.Message = "缓存过期，请重新登录"
                context.Response.Write(JsonConvert.SerializeObject(result))
                Exit Sub
            End If
            Select Case action
                Case "GetContainerStepCheckList" '获取待检批次列表
                    GetContainerStepCheckList(context)
                Case "GetContainerDetailInfo" '批次详细
                    GetContainerDetailInfo(context)
                Case "SaveStepCheckData" '保存流水卡检验
                    SaveStepCheckData(context)
                Case "GetContainerSecondCheckList" '获取二检批次列表
                    GetContainerSecondCheckList(context)
                Case "SaveContainerSecondCheck" '保存二检数据
                    SaveContainerSecondCheck(context)
                Case "SetInputCheckPoint" '设置二检检测项缓存
                    SetInputCheckPoint(context)
                Case Else
                    result.Result = False
                    result.Message = "方法不明确"
                    context.Response.Write(JsonConvert.SerializeObject(result))
            End Select
        Catch ex As Exception
            result.Result = False
            result.Message = ex.Message
            context.Response.ContentType = "text/html"
            context.Response.Write(JsonConvert.SerializeObject(result))
        End Try
    End Sub
    
    ''' <summary>
    ''' 获取待二检的批次
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub GetContainerSecondCheckList(ByVal context As HttpContext)
        Dim result As New uMESProcessResult()
        result.Result = True
        If Not m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "首件二检") = "是" Then
            result.Result = False
            result.Message = "分厂没有二检属性"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        Dim para As New Dictionary(Of String, String)
        para.Add("factoryID", m_UserInfo.FactoryID)
        para.Add("ScanContainerName", context.Request("scanContainer").ToString)
        If Not String.IsNullOrWhiteSpace(para("ScanContainerName").ToString) Then
            para("ScanContainerName") = m_Common.ContainerScan(para("ScanContainerName").ToString)
        End If
        para.Add("ScanOrderName", context.Request("scanOrder").ToString)
        para.Add("ProductName", context.Request("productName").ToString)
        para.Add("ContainerName", context.Request("containerName").ToString)
        para.Add("StepName", context.Request("stepName").ToString)
        para.Add("PageSize", context.Request("pageSize").ToString)
        para.Add("PageIndex", context.Request("pageIndex").ToString)
        result = checkBusiness.GetContainerSecondCheckList(para)
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    
    ''' <summary>
    ''' 二检确认
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub SaveContainerSecondCheck(ByVal context As HttpContext)
        Dim result As New uMESProcessResult()
        '检验批次
        Dim dtContainer As DataTable = JsonConvert.DeserializeObject(Of DataTable)(context.Request("paramDt").ToString())
        If dtContainer.Rows.Count = 0 Then
            result.Result = False
            result.Message = "没有选择批次"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        For Each dr As DataRow In dtContainer.Rows
            Dim reportId As String = dr("ContainerStepWorkReportID").ToString
            Dim exuteEntity = New ExcuteEntity("containerstepworkreport", ExcuteEntity.ExcuteTypeEnum.update)
            exuteEntity.ExcuteFileds = New List(Of FieldEntity) From {New FieldEntity("secondcheckempid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str),
                                                                      New FieldEntity("secondcheckdate", Date.Now, FieldEntity.FieldTypeEnum.DateTime)}
            exuteEntity.WhereFileds = New List(Of FieldEntity) From {New FieldEntity("containerstepworkreportid", reportId, FieldEntity.FieldTypeEnum.Str)}
            If Not DatabaseHelper.ExecuteDataByEntity(exuteEntity) Then
                result.Result = False
                result.Message = "批次:" + dr("ContainerName").ToString + "二检失败"
                context.Response.Write(JsonConvert.SerializeObject(result))
                Exit For
            End If
        Next
        result.Result = True
        result.Message = "二检成功"
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    ''' <summary>
    ''' 设置检测项缓存
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub SetInputCheckPoint(ByVal context As HttpContext)
        Dim result As New uMESProcessResult()
        '检验批次
        Dim dtContainer As DataTable = JsonConvert.DeserializeObject(Of DataTable)(context.Request("mainDt").ToString())
        If dtContainer.Rows.Count = 0 Then
            result.Result = False
            result.Message = "没有选择批次"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        Dim msg = ""
        For Each dr As DataRow In dtContainer.Rows
            If m_Common.JudeContainerHold(dr("ContainerId").ToString(), msg) Then
                result.Result = False
                result.Message = "该批次已暂停，暂停原因：" + msg
                context.Response.Write(JsonConvert.SerializeObject(result))
                Exit Sub
            End If
        Next
        context.Session("PopupData") = dtContainer
        result.Result = True
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    
    ''' <summary>
    ''' 获取待检验批次列表
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub GetContainerStepCheckList(ByVal context As HttpContext)
        Dim result As New uMESProcessResult()
        result.Result = True
        Dim para As New Dictionary(Of String, String)
        If m_UserInfo.FactoryID Is Nothing Then
            result.Result = False
            result.Message = "缓存过期"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        para.Add("FactoryID", m_UserInfo.FactoryID)
        para.Add("PageSize", context.Request("pageSize").ToString())
        para.Add("PageIndex", context.Request("pageIndex").ToString())
        para.Add("ContainerName", context.Request("containerName").ToString())
        Dim scanStr As String = context.Request("scanContainer").ToString()
        If Not String.IsNullOrWhiteSpace(scanStr) Then
            para("ScanContainerName") = m_Common.ContainerScan(scanStr)
        End If
        Dim strSelectChecker As String = ""
        strSelectChecker = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "报工选择检验") '获取工厂报工是否选择检验员信息
        If strSelectChecker = "是" Then
            para.Add("CheckerID", m_UserInfo.EmployeeID)
        End If
        '获取数据
        result = checkBusiness.GetNewContainerCheckList(para)
        If result.Result And result.DBTable.Rows.Count = 0 Then
            result.Message = "没有数据"
            result.Result = False
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    ''' <summary>
    ''' 获取批次详细信息
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub GetContainerDetailInfo(ByVal context As HttpContext)
        Dim result As New uMESProcessResult()
        result.Result = True
        Dim containerId As String = context.Request("containerId").ToString()
        Dim dic As New Dictionary(Of String, String)
        dic.Add("Containerid", containerId)

        Dim PR As uMESProcessResult = oIBusiness.GetContainerPrintInfo(dic)
        
        dic.Add("FactoryID", m_UserInfo.FactoryID)
        stepWorkReportDt = checkBusiness.GetNewStepCheckByContainer(dic) '查询该批次的已报工序（且未检验的）
        
        '工艺员查询
        strTechniqueEmp = PR.DBDataSet.Tables("dtMain").Rows(0)("TECHNIQUEEMPLOYNAME").ToString
        strProductName = PR.DBDataSet.Tables("dtMain").Rows(0)("productname").ToString()
        strPlanName = PR.DBDataSet.Tables("dtMain").Rows(0)("PlanFullName").ToString
        wfFactoryName = PR.DBDataSet.Tables("dtMain").Rows(0)("wffactoryname").ToString() '工艺分厂
        
        result.ReturnData = IniPrintInfo(PR, False)
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    ''' <summary>
    ''' 填充打印信息
    ''' </summary>
    ''' <param name="PR"></param>
    ''' <remarks></remarks>
    Private Function IniPrintInfo(ByVal PR As uMESProcessResult, ByVal IsSubWorkflow As Boolean) As String
        Dim Originalqty = PR.DBDataSet.Tables("dtMain").Rows(0)("Originalqty").ToString()
        Dim conType As Integer = Val(PR.DBDataSet.Tables("dtMain").Rows(0)("CONTAINERTYPE").ToString())
        strMfgordername = PR.DBDataSet.Tables("dtMain").Rows(0)("Mfgordername").ToString()
        isselfmfg = If(PR.DBDataSet.Tables("dtMain").Rows(0)("isselfmfg").ToString() = "0", True, False)
        startDate = PR.DBDataSet.Tables("dtMain").Rows(0)("originalstartdate").ToString()
        Dim gys As String = GetDataValue(PR.DBDataSet.Tables("dtDataPoint"), "供应商", False)
        '产品特性 add:Wangjh 20150517
        partCharacterType = PR.DBDataSet.Tables("dtMain").Rows(0)("charactertype").ToString()
        If partCharacterType <> "关键件" And partCharacterType <> "重要件" Then
            partCharacterType = ""
        End If
        '
        Dim strHtmlTitle As String = SetTableTitle(conType, partCharacterType, startDate, gys)
        Dim strHtmlTableMain As String = SetTableMain(PR, Originalqty)
        Dim strHtmlTableDetails As String = SetTableDetail(PR, Originalqty)
        Return String.Format("{0}{1}{2}", strHtmlTitle, strHtmlTableMain, strHtmlTableDetails)
    End Function
    ''' <summary>
    ''' 生成表头
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SetTableTitle(ByVal type As Integer, ByVal partCharacterType As String, ByVal originalstartdate As String, ByVal gys As String) As String

        Dim parttype As String = If(isselfmfg, "零件", "组件")
        If Not String.IsNullOrWhiteSpace(originalstartdate) Then
            originalstartdate = DateTime.Parse(originalstartdate).ToString("yyyy年MM月dd日")
        End If
        Dim sb As New StringBuilder()
        sb.Append("<table class=table1 >")
        sb.Append("<tr><th colspan=3 valign='bottom' style='height:60px;text-align: center;position:relative'>")
        If parttype = "零件" Then
            sb.AppendLine("<div style='width:100%;height:36px;text-align:left;position:absolute;left:0;top:0px' ><div style='float:left'>供应商:</div><span style='text-align:left;font-weight:normal;'>" + gys + "</span></div>")
        End If
        If type = 7 Then
            sb.AppendFormat("<span style=font-size:32px;>单件加工{0}工艺流水卡片</span><div style='float:right;margin-top:10px'>" + partCharacterType + "</div></th></tr>", parttype)
        Else
            sb.AppendFormat("<span style=font-size:32px;>批量加工{0}工艺流水卡片</span><div style='float:right;margin-top:10px'>" + partCharacterType + "</div></th></tr>", parttype)
        End If

        sb.AppendFormat("<tr><td style='text-align: left;padding-left:10px;'>{0}</td>", wfFactoryName) 'update:Wangjh 2017-7-6 将工厂更改为当前用户所属的 20180927更改为工艺分厂
        sb.AppendFormat("<td style='text-align: center'> {0} </td>", originalstartdate)
        sb.Append("</tr></table>")
        SetTableTitle = sb.ToString
    End Function

    ''' <summary>
    ''' 生成流水卡信息
    ''' </summary>
    ''' <param name="PR"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SetTableMain(ByVal PR As uMESProcessResult, ByVal Originalqty As Integer) As String
        Dim dtMain As DataTable = PR.DBDataSet.Tables("dtMain")
        Dim sbHtml As New StringBuilder
        Dim productName = dtMain.Rows(0)("Productname").ToString()
        Dim ProductDesc = dtMain.Rows(0)("ProductDesc").ToString()
        Dim workflowRoute As String = dtMain.Rows(0)("workflowroute").ToString() '分段件号
        Dim familyName = dtMain.Rows(0)("familylistnames")
        Dim partRev As String = dtMain.Rows(0)("Part_RevID").ToString '设计图版次 
        Dim prosseRev As String = dtMain.Rows(0)("ly2sequence").ToString '工艺规程版次 

        'Modify by Yuxj20200528 型号包含WP,全通，但是不包含WP，设计图版次和工艺版次打印斜杠
        If (familyName.ToString.Contains("WP") Or familyName.ToString.Contains("全通")) And (Not familyName.ToString.Contains("WS")) And (Not familyName.ToString.Contains("KWP2")) Then
            partRev = "/"
            prosseRev = "/"
        End If

        'yuxj20221028临时工艺判断
        'Dim workflowType As String = dtMain.Rows(0)("WorkflowType").ToString '工艺类型
        Dim workflowType2 As String = dtMain.Rows(0)("WorkflowType2").ToString '工艺类型
        Dim prosseNo As String = dtMain.Rows(0)("process_no").ToString '原始工艺号

        If workflowType2.Trim <> "临时工艺" Then
            prosseNo = ""
        End If
        Dim wfFactoryID = dtMain.Rows(0)("wffactoryid").ToString()
        wfFactoryName = dtMain.Rows(0)("wffactoryname").ToString()
        bomPersonMerge = m_Common.GetFatoryAttributes(wfFactoryID, "配套表人员合并")
        Dim Containername = dtMain.Rows(0)("Containername").ToString()
        strContainerName = Containername
        sbHtml.Append("<table class='table2' ><tr ><td width='110' >设计图版次</td><td width='60'>" + partRev + "</td><td width='110'>工艺规程版次</td><td width='60'>" + prosseRev + "</td><td width='120'>临时工艺规程编号</td><td>" + prosseNo + "</td></tr></table>")
        sbHtml.Append("<table class='table2'>")
        Dim dtDataPoint As DataTable = PR.DBDataSet.Tables("dtDataPoint")
        If Not String.IsNullOrWhiteSpace(workflowRoute) Then
            strProductName = workflowRoute
        End If
        If wfFactoryName.Contains("机匣") And dtDataPoint.Select("dataname='ChildWFContianer'").Length > 0 Then
            strProductName += "(H)"
        End If

        If isselfmfg Then '零件
            sbHtml.AppendFormat("<tr><td colspan=2>生产订单号</td><td colspan=2>{0}</td><td colspan=2>批次号</td><td colspan=2>{1}</td></tr>", strMfgordername, Containername.Replace(productName + "/", ""))
            Dim Originalstartdate = dtMain.Rows(0)("Originalstartdate").ToString()
            Dim Materialtrademark = dtMain.Rows(0)("PlanMaterialtrademark").ToString '材料牌号
            Dim MaterialSpecification = dtMain.Rows(0)("PlanMaterialSpecification").ToString '材料规格
            Dim materialSize = dtMain.Rows(0)("materialSize").ToString '毛料规格
            Dim strMaterialtEmp As String = "" '库房保管
            Dim strmaterialCheckEmp As String = "" '器材检验

            Dim strFilter As String = "dataname='实发数/顺序号'"
            Dim tmpRows As DataRow() = dtDataPoint.Select(strFilter)
            Dim shifa As String = ""
            If tmpRows.Length > 0 Then
                If tmpRows(0).IsNull("datavalue") = False Then
                    shifa = tmpRows(0)("datavalue").ToString()
                End If
                If tmpRows(0).IsNull("splitfromid") = False Then '如果该批次是由分批而来的实发数就是分批数 add:Wangjh 2017-7-25
                    shifa = tmpRows(0)("originalqty").ToString()
                End If
            End If

            Dim rongluChild As String = GetDataValue(dtDataPoint, "熔炉号子")
            Dim rongluP As String = GetDataValue(dtDataPoint, "熔炉号母")
            Dim jianyan As String = GetDataValue(dtDataPoint, "检验编号")
            Dim paihao As String = GetDataValue(dtDataPoint, "代料牌号", True)
            Dim paihaoge As String = GetDataValue(dtDataPoint, "代料规格", True)
            Dim danhao As String = GetDataValue(dtDataPoint, "代料单号", True)
            Dim pingxing As String = GetDataValue(dtDataPoint, "平行作业工序", True)
            Dim pingxingBill As String = GetDataValue(dtDataPoint, "平行作业单号", True)

            strMaterialtEmp = GetDataValue(dtDataPoint, "库房保管")
            strmaterialCheckEmp = GetDataValue(dtDataPoint, "器材检验")
            sbHtml.Append("<tr><td width='90px'>零件号</td>")

            sbHtml.AppendFormat("<td width='110' id='pName'>{0}</td>", strProductName)

            sbHtml.AppendFormat("<td width='75'>名称</td><td width='120'>{0}</td>", ProductDesc)
            sbHtml.AppendFormat("<td width='55'>型别</td><td width='120' style='font-size: 12px'>{0}</td>", familyName)
            sbHtml.AppendFormat("<td width='65'>计划员</td><td width='100'>{0}</td></tr>", strPlanName)

            sbHtml.Append("<tr><td>熔炉号</td>")
            If String.IsNullOrWhiteSpace(rongluChild) And String.IsNullOrWhiteSpace(rongluP) Then
                sbHtml.Append("<td></td>")
            ElseIf String.IsNullOrWhiteSpace(rongluChild) Then
                sbHtml.AppendFormat("<td>{0}</td>", rongluP)
            ElseIf String.IsNullOrWhiteSpace(rongluP) Then
                sbHtml.AppendFormat("<td>{0}</td>", rongluChild)
            Else
                sbHtml.AppendFormat("<td style='font-size :small'>子：{0}</p>母：{1}</td>", rongluChild, rongluP)
            End If

            sbHtml.AppendFormat("<td>计划数</td><td>{0}</td>", Originalqty)
            sbHtml.AppendFormat("<td>实发数/顺序号</td><td>{0}</td>", shifa)
            sbHtml.AppendFormat("<td>工艺员</td><td>{0}</td></tr>", strTechniqueEmp)

            sbHtml.AppendFormat("<tr><td>材料牌号</td><td style='font-size: 12px'>{0}</td>", Materialtrademark)

            sbHtml.AppendFormat("<td>检&nbsp;验编&nbsp;号</td><td>{0}</td>", jianyan)
            sbHtml.AppendFormat("<td>库&nbsp;房保&nbsp;管</td><td>{0}</td>", strMaterialtEmp)
            'sbHtml.Append("<td>器&nbsp;材检&nbsp;验</td>")
            'If String.IsNullOrWhiteSpace(pingxingBill) Then
            '    sbHtml.AppendFormat("<td>{0}</td>", strmaterialCheckEmp)
            'Else
            '    sbHtml.Append("<td></td>")
            'End If
            sbHtml.AppendFormat("<td>器&nbsp;材检&nbsp;验</td><td>{0}</td>", strmaterialCheckEmp)
            sbHtml.Append("</tr>")

            sbHtml.AppendFormat("<td>材料规格</td><td style='font-size: 12px'>{0}</td>", MaterialSpecification)
            sbHtml.AppendFormat("<td>毛&nbsp;料规&nbsp;格</td><td style='font-size: 12px'>{0}</td>", materialSize)
            sbHtml.AppendFormat("<td>代&nbsp;料牌&nbsp;号</td><td>{0}</td>", paihao)
            sbHtml.AppendFormat("<td>代&nbsp;料规&nbsp;格</td><td>{0}</td></tr>", paihaoge)

            sbHtml.AppendFormat("<tr><td>代料单号</td><td>{0}</td>", danhao)
            'Modify by yuxj20200528 平行作业单->例外放行审批单号 平行作业工序->例外放行工序
            sbHtml.AppendFormat("<td>例外放行审批单号</td><td>{0}</td>", pingxingBill)
            sbHtml.AppendFormat("<td>例外放行工序</td><td>{0}</td>", pingxing) '
            sbHtml.Append("<td>分&nbsp;厂检&nbsp;验</td>")
            If dtDataPoint.Rows(0).IsNull("splitfromid") = False Then '如果该批次是由分批而来的 add:Wangjh 2017-7-25
                sbHtml.AppendFormat("<td>{0}</td>", dtDataPoint.Rows(0)("checkemployeeName").ToString())
            Else
                'sbHtml.Append("<td></td>")
                'add zhunan 2021.1.18 增加显示【分厂检验】（取第一道工序实际的检验员）
                Dim fcjy As String = ""
                If PR.DBDataSet.Tables("dtContainerStep").Columns.Contains("checkemployeename") Then
                    Dim temp = PR.DBDataSet.Tables("dtContainerStep").Select("factoryid='" + wfFactoryID + "'")
                    If temp.Length > 0 Then
                        fcjy = temp(0)("checkemployeename").ToString
                    End If
                End If
                sbHtml.AppendFormat("<td>{0}</td>", fcjy)
            End If
            sbHtml.Append("</tr>")

            'add zhunan 2021.1.18 打印顾客代表、热表批次号
            Dim gkdb As String = GetDataValue(dtDataPoint, "顾客代表")
            sbHtml.Append("<tr>")
            Dim dtRbContainerList As DataTable = PR.DBDataSet.Tables("dtRbContainerList") '热表批次号
            If dtRbContainerList.Rows.Count = 0 Then
                sbHtml.Append("<td colspan=1>热表批次</td> <td colspan=2></td> <td colspan=2></td> <td colspan=1></td>")
            ElseIf dtRbContainerList.Rows.Count = 1 Then
                sbHtml.AppendFormat("<td colspan=1>热表批次</td> <td colspan=2>{0}</td><td colspan=2></td><td colspan=1></td>", dtRbContainerList.Rows(0)("rbtogetherflag").ToString())
            ElseIf dtRbContainerList.Rows.Count = 2 Then
                sbHtml.AppendFormat("<td colspan=1>热表批次</td> <td colspan=2>{0}</td><td colspan=2>{1}</td><td colspan=1></td>",
                                    dtRbContainerList.Rows(0)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(1)("rbtogetherflag").ToString())
            Else
                sbHtml.AppendFormat("<td colspan=1>热表批次</td> <td colspan=2>{0}</td><td colspan=2>{1}</td><td colspan=1>{2}</td>",
                                    dtRbContainerList.Rows(0)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(1)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(2)("rbtogetherflag").ToString())
            End If

            sbHtml.AppendFormat("<td colspan=1>顾&nbsp;客代&nbsp;表</td><td colspan=1>{0}</td>", gkdb)
            sbHtml.Append("</tr>")

            '追加不合格审理单号 add by zhangrj 2022-2-23
            Dim unQualifiedNum As String = GetDataValue(dtDataPoint, "不合格审理单号", True)
            sbHtml.AppendFormat("<tr><td colspan=2>不合格审理单号</td><td colspan=6>{0}</td></tr>", unQualifiedNum)
        Else '组件
            sbHtml.AppendFormat("<tr><td colspan=4>生产订单号</td><td colspan=4>{0}</td></tr>", strMfgordername)
            sbHtml.Append("<tr><td width='60'>组合件号</td>")

            sbHtml.AppendFormat("<td width='120' id='pName'>{0}</td>", strProductName)

            sbHtml.AppendFormat("<td width='55'>名称</td><td width='120'>{0}</td>", ProductDesc)
            sbHtml.AppendFormat("<td width='55'>型别</td><td colspan=3 style ='font-size :10px'>{0}</td></tr>", familyName)
            sbHtml.AppendFormat("<tr><td>批次号</td><td>{0}</td>", Containername.Replace(productName + "/", ""))
            sbHtml.AppendFormat("<td>数量</td><td>{0}</td>", Originalqty)
            sbHtml.AppendFormat("<td>计划员</td><td width='55'>{0}</td>", strPlanName)
            sbHtml.AppendFormat("<td width='55'>工艺员</td><td width='55'>{0}</td></tr>", strTechniqueEmp)
            ' sbHtml.AppendLine("<tr><td colspan=1>热表批次</td><td colspan=1></td><td colspan=2></td><td colspan=2></td><td colspan=1>顾&nbsp;客代&nbsp;表</td><td colspan=1></td></tr>")
            'sbHtml.AppendLine("<tr><td colspan=2>热表批次</td><td colspan=2></td><td colspan=2></td><td colspan=2></td></tr>")
            Dim dtRbContainerList As DataTable = PR.DBDataSet.Tables("dtRbContainerList") '热表批次号
            If dtRbContainerList.Rows.Count = 0 Then
                sbHtml.Append("<td colspan=2>热表批次</td> <td colspan=2></td> <td colspan=2></td> <td colspan=2></td>")
            ElseIf dtRbContainerList.Rows.Count = 1 Then
                sbHtml.AppendFormat("<td colspan=2>热表批次</td> <td colspan=2>{0}</td><td colspan=2></td><td colspan=2></td>", dtRbContainerList.Rows(0)("rbtogetherflag").ToString())
            ElseIf dtRbContainerList.Rows.Count = 2 Then
                sbHtml.AppendFormat("<td colspan=2>热表批次</td> <td colspan=2>{0}</td><td colspan=2>{1}</td><td colspan=2></td>",
                                    dtRbContainerList.Rows(0)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(1)("rbtogetherflag").ToString())
            Else
                sbHtml.AppendFormat("<td colspan=2>热表批次</td> <td colspan=2>{0}</td><td colspan=2>{1}</td><td colspan=2>{2}</td>",
                                    dtRbContainerList.Rows(0)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(1)("rbtogetherflag").ToString(),
                                    dtRbContainerList.Rows(2)("rbtogetherflag").ToString())
            End If
        End If

        sbHtml.Append("</table>")


        SetTableMain = sbHtml.ToString()
    End Function
    
    ''' <summary>
    ''' 生成流水卡工序
    ''' </summary> 
    ''' <param name="PR"></param>
    ''' <param name="qty"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SetTableDetail(ByVal PR As uMESProcessResult, ByVal qty As Integer) As String
        SetTableDetail = String.Empty
        Try
            Dim dtMain As DataTable = PR.DBDataSet.Tables("dtMain")
            Dim dtContainerStep As DataTable = PR.DBDataSet.Tables("dtContainerStep")
            'Dim dtCheckItemList As DataTable = PR.DBDataSet.Tables("dtCheckItemList")
            Dim conType As Integer = Val(PR.DBDataSet.Tables("dtMain").Rows(0)("CONTAINERTYPE").ToString())
            Dim wipQty = dtMain.Rows(0)("qty").ToString

            Dim strProdcut As String = dtMain.Rows(0)("productname").ToString().Trim()
            Dim strMemo As String = ""
            '得到关闭备注信息
            Dim strCloseContainer As String = ""
            If dtMain.Rows(0).IsNull("CloseContianer") = False Then
                strCloseContainer = dtMain.Rows(0)("CloseContianer").ToString().Trim()
                strMemo = oIBusiness.GetColseMemo(strCloseContainer)
            End If
            '得到开始工序
            '得到关闭备注信息
            Dim strBeginStepName As String = ""
            If dtMain.Rows(0).IsNull("BeginStep") = False Then
                strBeginStepName = dtMain.Rows(0)("BeginStep").ToString().Trim()
            End If
            Dim sbHtml As New StringBuilder
         
            Dim specname = String.Empty
            Dim specid = String.Empty
            Dim stepid = String.Empty
            Dim sequenceNO = String.Empty
            Dim stepName As String = ""

            sbHtml.Append(SetTableSpecHeader(True))

            For i As Integer = 0 To dtContainerStep.Rows.Count - 1
                Dim sbSpecHtml As New StringBuilder
                Dim strBmemo As String = ""
                specname = String.Empty
                specid = String.Empty
                sequenceNO = String.Empty
                stepName = String.Empty 'add:Wangjh 2017-8-4
                stepid = String.Empty
                SetSpecNameInfo(specname, stepid, specid, stepName, sequenceNO, dtContainerStep.Rows(i))
                sbSpecHtml.Append(SetSpecInfo(specname, sequenceNO, stepid, wipQty, strBmemo, dtContainerStep, i))
                sbHtml.Append(sbSpecHtml.ToString)
            Next
            sbHtml.Append("</table>")
            SetTableDetail = sbHtml.ToString()
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    
    ''' <summary>
    ''' 生产工序表头
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SetTableSpecHeader(ByVal isfirstpage As Boolean) As String
        Dim sbTable3Header As New StringBuilder
        If isfirstpage Then
            sbTable3Header.Append("<table id=originaltable class=table3 style='BORDER-TOP: medium none;'>")
        Else
            sbTable3Header.Append("<table id=originaltable class=table3 style='BORDER-TOP: medium none;PAGE-BREAK-AFTER: always'>")
        End If
        sbTable3Header.Append("<tr><td rowspan=2 width='65'><div class=t_1>工序</div></td>")
        sbTable3Header.Append("<td rowspan=2 width='150'>名称</td>")
        sbTable3Header.Append("<td rowspan=2 width='35'>数量</td>")
        sbTable3Header.Append("<td colspan=4>自检结果（件数）</td>")

        sbTable3Header.Append("<td rowspan=2 width='80'>加&nbsp;&nbsp;工日&nbsp;&nbsp;期</td>")
        sbTable3Header.Append("<td  rowspan=2 width='35' style='BORDER-RIGHT: medium none'>工</td>")
        sbTable3Header.Append("<td  rowspan=2 width='45' style='BORDER-LEFT: medium none'>人</td>")
        sbTable3Header.Append("<td rowspan=2 width='55'>检验印</td>")
        sbTable3Header.Append("<td rowspan=2 width='105'>备注</td>")
        sbTable3Header.Append("<tr><td width='30'><div class=t_2>合格</div></td>")
        sbTable3Header.Append("<td width='30'><div class=t_2>报废</div></td>")
        sbTable3Header.Append("<td width='30'><div class=t_2>超差</div></td>")
        sbTable3Header.Append("<td width='30'><div class=t_2>返修</div></td></tr>")
        SetTableSpecHeader = sbTable3Header.ToString
    End Function
    
    ''' <summary>
    ''' 工序基本信息处理
    ''' </summary>
    ''' <param name="specname"></param>
    ''' <param name="specid"></param>
    ''' <param name="stepName"></param>
    ''' <param name="sequenceNO"></param>
    ''' <param name="dr"></param>
    ''' <remarks></remarks>
    Private Sub SetSpecNameInfo(ByRef specname As String, ByRef stepid As String, ByRef specid As String, ByRef stepName As String, ByRef sequenceNO As String, ByVal dr As DataRow)

        specname = dr("specname").ToString()
        specid = dr("specid").ToString()
        stepName = dr("workflowstepname").ToString()
        stepid = dr("workflowstepid").ToString
        If String.IsNullOrWhiteSpace(specname) Then 'add:Wangjh 2017-8-3 
            specname = stepName
        End If

        Dim arrTemp = stepName.Split("-")
        sequenceNO = arrTemp(0)
        specname = stepName.Replace(sequenceNO + "-", "")

        If Not String.IsNullOrWhiteSpace(dr("opdesc").ToString()) Then
            specname = dr("opdesc").ToString()
        End If
        '

        'add:Wangjh 增加工序号和工序名赋值 20171206
        If Not String.IsNullOrWhiteSpace(dr("specno").ToString()) Then
            sequenceNO = dr("specno").ToString()
        End If
        '处理工序号位数
        Try
            If IsNumeric(sequenceNO) Then
                sequenceNO = Integer.Parse(sequenceNO).ToString
            End If
        Catch ex As Exception

        End Try

        '关键工序，在工序号前加G
        If dr("iskey").ToString() = "1" Then
            sequenceNO = "G" + sequenceNO
        End If
    End Sub
    
    ''' <summary>
    ''' 生成工序表格
    ''' </summary>
    ''' <param name="specname">工序名</param>
    ''' <param name="sequenceNO">工序号</param>
    ''' <param name="stepid">工序ID</param>
    ''' <param name="wipQty">在制数</param>
    ''' <param name="strBmemo">备注</param>
    ''' <param name="dtContainerStep">工序列表</param>
    ''' <param name="i">行数</param>    
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SetSpecInfo(ByVal specname As String, ByVal sequenceNO As String, ByVal stepid As String, ByVal wipQty As String, ByVal strBmemo As String, ByVal dtContainerStep As DataTable, ByVal i As Integer) As String
        Dim sbSpecHtml As New StringBuilder
        If Not dtContainerStep.Columns.Contains("reportdate") Then
            dtContainerStep.Columns.Add("reportdate")
        End If
        '报工
        Dim drsReport As DataRow() = dtContainerStep.Select(" workflowstepid='" + stepid + "' and reportdate is not null")
        ' Dim dicField = GetDetailsField(drsReport, drsQuality, drsSpecLastCheck, drsConventionCheck)
        sbSpecHtml.AppendFormat("<tr idtype=spec  ><td rowspan=1>{0}</td><td rowspan=1 class=t_4", sequenceNO)

        If specname.Length > 15 Then
            sbSpecHtml.Append(" style='font-size: 10px'>")
        Else
            sbSpecHtml.Append(">")
        End If
        sbSpecHtml.AppendFormat("{0}</td>", specname)
        '添加检验备注 add zhangrj 20220608
        If stepid <> "" Then
            Dim drsCheckNotes As DataRow() = dtContainerStep.Select("workflowstepid='" + stepid + "'")
            strBmemo += drsCheckNotes(0)("NOTES").ToString + ","

            If dtContainerStep.Columns.Contains("ISCOMMISSION") Then
                If drsCheckNotes(0)("CONTROLCODE").ToString() = "LY05" Or drsCheckNotes(0)("ISCOMMISSION").ToString() = "1" Then
                    strBmemo += "外委加工,"
                End If
            End If
            For Each cknote As DataRow In drsCheckNotes
                If Not String.IsNullOrWhiteSpace(cknote("CHECKNOTE").ToString) Then
                    strBmemo += cknote("CHECKNOTE").ToString + ","
                End If
                If Not String.IsNullOrWhiteSpace(cknote("WORKNOTE").ToString) Then
                    strBmemo += cknote("WORKNOTE").ToString + ","
                End If
            Next
            strBmemo = strBmemo.Trim(",")
        End If
        '如果没有报工数据
        If drsReport.Length = 0 Then
            sbSpecHtml.Append("<td></td><td></td><td></td><td></td><td></td><td></td><td colspan=2></td><td></td><td style='text-align: left;font-size: 10px'>" + strBmemo + "</td>")
        Else
            Dim strTmpMemo As String = ""
            If dtContainerStep.Rows(i)("checktype").ToString = "3" Then '试验件报工
                strTmpMemo = "试件报工:" & dtContainerStep.Rows(i)("ReportQty").ToString + ","
                dtContainerStep.Rows(i)("ReportQty") = wipQty
                dtContainerStep.Rows(i)("passqty") = wipQty
                dtContainerStep.Rows(i)("lossqty") = DBNull.Value
            End If
            Dim reportDate As String = ""
            If Not dtContainerStep(i).IsNull("reportdate") Then
                reportDate = DateTime.Parse(dtContainerStep(i)("reportdate")).ToString("yyyy/MM/dd")
            End If

            sbSpecHtml.Append("<td>" + dtContainerStep.Rows(i)("ReportQty").ToString + "</td><td style='")
            sbSpecHtml.Append("'>" + dtContainerStep.Rows(i)("passqty").ToString + "</td><td>" + dtContainerStep.Rows(i)("lossqty").ToString + "</td>")
            sbSpecHtml.Append("<td>" + dtContainerStep.Rows(i)("defectqty").ToString + "</td><td>" + dtContainerStep.Rows(i)("ReworkQty").ToString + "</td><td>" + reportDate + "</td>")

            sbSpecHtml.Append("<td colspan=2 style='")
            If dtContainerStep.Rows(i)("ReportEmployeeName").ToString.Length > 6 Then
                sbSpecHtml.Append(" font-size: 10px")
            End If

            '检验工序 报工人显示横岗
            If dtContainerStep.Rows(i)("LASTCHECK").ToString = "1" Or dtContainerStep.Rows(i)("CONTROLCODE").ToString = "LY05" Then
                sbSpecHtml.Append("'>" + "--" + "</td><td style='")
            Else
                sbSpecHtml.Append("'>" + dtContainerStep.Rows(i)("ReportEmployeeName").ToString + "</td><td style='")
            End If
            
            Dim drs As DataRow() = stepWorkReportDt.Select("workflowstepid='" + stepid + "' and containerstepworkreportid='" + dtContainerStep.Rows(i)("containerstepworkreportid").ToString + "'")
            '工序存在已报工未检验，添加检验按钮
            If drs.Length > 0 Then
                'strBmemo = "<input class='easyui-textbox' style='width: 150px; height: 22px' />" '备注输入框
                '检验按钮
                Dim checkBtn As String = "<a class='easyui-linkbutton' style='width:80px' data-stepid='" + stepid + "' data-reportid='" + drs(0)("containerstepworkreportid").ToString() + "' data-checktype='" + drs(0)("checktype").ToString() + "'>检验</a>"
                sbSpecHtml.Append("'>" + checkBtn + "</td><td style='text-align: left;")
            Else
                If dtContainerStep.Rows(i)("CONTROLCODE").ToString = "LY05" Then
                    sbSpecHtml.Append("'>" + "--" + "</td><td style='text-align: left;")
                Else
                    If dtContainerStep.Rows(i)("checkemployeename").ToString.Length > 6 Then
                        sbSpecHtml.Append(" font-size: 10px")
                    End If
                    sbSpecHtml.Append("'>" + dtContainerStep.Rows(i)("checkemployeename").ToString + "</td><td style='text-align: left;")
                End If
            End If
            strTmpMemo += strBmemo
            strTmpMemo = strTmpMemo.Trim(",")
            If strTmpMemo.Length > 11 Then
                sbSpecHtml.Append(" font-size: 10px")
            End If
            sbSpecHtml.Append("'>" + strTmpMemo + "</td>")
        End If

        sbSpecHtml.Append("</tr>")
        Return sbSpecHtml.ToString()
    End Function
    
    Private Function GetDataValue(ByVal dtDataPoint As DataTable, ByVal strName As String) As String
        Dim strFilter As String = "dataname='熔炉号子'"
        Dim tmpRows As DataRow() = dtDataPoint.Select(String.Format("dataname='{0}'", strName))
        GetDataValue = ""
        If tmpRows.Length > 0 Then
            If tmpRows(0).IsNull("datavalue") = False Then
                GetDataValue = tmpRows(0)("datavalue").ToString()
            End If
        End If
    End Function
    
    Private Function GetDataValue(ByVal dtDataPoint As DataTable, ByVal strName As String, ByVal IsDefault As Boolean) As String
        Dim strFilter As String = "dataname='熔炉号子'"
        Dim tmpRows As DataRow() = dtDataPoint.Select(String.Format("dataname='{0}'", strName))
        If IsDefault Then
            GetDataValue = "----------"
        Else
            GetDataValue = ""
        End If

        If tmpRows.Length > 0 Then
            If tmpRows(0).IsNull("datavalue") = False Then
                GetDataValue = tmpRows(0)("datavalue").ToString()
            End If
        End If
    End Function
    ''' <summary>
    ''' 保存检验数据
    ''' </summary>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub SaveStepCheckData(ByVal context As HttpContext)
        Dim result = New uMESProcessResult()
        result.Result = True
        result.Message = "检验成功"
        If m_UserInfo.FactoryID Is Nothing Then
            result.Result = False
            result.Message = "缓存过期"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        If Not m_UserInfo.Roles.Contains("检验员") Then
            result.Result = False
            result.Message = "当前登录人员非检验员，请重新登录"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        Dim host As New ServerHostInfo
        host.UserName = m_UserInfo.APIUserName
        host.Password = m_UserInfo.APIPassword
        Dim levelAttributes As DataTable = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID)
        '检验批次工序
        Dim dtContainer As DataTable = JsonConvert.DeserializeObject(Of DataTable)(context.Request("paramDt").ToString())
        If dtContainer.Rows.Count = 0 Then
            result.Result = False
            result.Message = "没有选择批次"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        If Not checkBusiness.IsInputCheckPointResult(dtContainer) Then
            result.Result = False
            result.Message = "存在未录入的实测值，请点击实测值录入"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        '验证是否无效的特殊工程工序 add by zhangrj 20250331
        Dim srvDto As SpecialReportValidDTO = checkBusiness.IsInvalidSpecialCourseSpecReportByCheck(dtContainer, m_UserInfo)
        If Not srvDto.IsValid Then
            result.Result = False
            result.Message = srvDto.Message
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        If srvDto.IsUnder95Day Then '如果有效期低于95天，提示
            result.Message += "，" + srvDto.Message
        End If

        Dim container As DataRow = dtContainer.Rows(0)
        Dim msg As String = ""
        If m_Common.JudeContainerHold(container("ContainerId").ToString(), msg) Then
            result.Result = False
            result.Message = "该批次已暂停，暂停原因：" + msg
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
       
        If String.IsNullOrWhiteSpace(container("ContainerStepWorkReportID").ToString) Then
            result.Result = False
            result.Message = "没有报工数据"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        '查询是否无效报工
        If Not checkBusiness.IsVaildWorkReportForCheck(container("ContainerStepWorkReportID").ToString, 1) Then
            result.Result = False
            result.Message = "存在撤销的报工数据，请刷新页面"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        If container("CheckType").ToString <> "1" And container("Firstchecknum").ToString = "1" Then
            result.Result = False
            result.Message = "批次有首检未检验，需先首检"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        If m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "首件二检") = "是" Then
            Dim exuteEntity = New ExcuteEntity("containerstepworkreport", ExcuteEntity.ExcuteTypeEnum.selectAll)


            exuteEntity.WhereFileds = New List(Of FieldEntity) From {New FieldEntity("containerid", container("ContainerId").ToString, FieldEntity.FieldTypeEnum.Str),
                                                                     New FieldEntity("workflowstepid", container("WorkflowstepID").ToString, FieldEntity.FieldTypeEnum.Str),
                                                                     New FieldEntity("CheckType", 1, FieldEntity.FieldTypeEnum.Numer),
                                                                     New FieldEntity("isuse", 0, FieldEntity.FieldTypeEnum.Numer)}
            exuteEntity.strWhere = " and SecondCheckDate is not null "
            Dim dt As DataTable = DatabaseHelper.QueryDataByEntity(exuteEntity)
            If container("Firstchecknum").ToString = "1" And dt.Rows.Count = 0 Then
                result.Result = False
                result.Message = "存在没有进行二检的首件报工"
                context.Response.Write(JsonConvert.SerializeObject(result))
                Exit Sub
            End If
        End If

        Dim dtCheck As DataTable = checkBusiness.ContainerCheckValidateList(container("ContainerStepWorkReportID").ToString, 0)
        
        If dtCheck.Rows.Count > 0 Then
            result.Result = False
            result.Message = "该报工已经检验，请刷新页面"
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        Dim para As New List(Of Dictionary(Of String, Object))
        '报工人为空
        If String.IsNullOrWhiteSpace(container("WorkEmployeeName").ToString) Then
            Dim dic As New Dictionary(Of String, Object)
            dic("FactoryID") = m_UserInfo.FactoryID
            dic("WorkerID") = m_UserInfo.EmployeeID
            dic("ContainerStepWorkReportID") = container("ContainerStepWorkReportID").ToString()
            para.Add(dic)
        End If

        Dim checkData As New List(Of ContainerCheckInfoDTO)
        Dim checkDto As New ContainerCheckInfoDTO
        checkDto.DefectQty = 0 '超差数
        checkDto.ReworkQty = 0 '返修数
        checkDto.LossQty = 0 '报废数
        checkDto.CheckQty = container("Qty").ToString '检验数量等于报工数量
        checkDto.WIPQty = container("WIPQTY").ToString '在制数
        checkDto.AcceptanceQty = container("Qty").ToString '合格数量等于报工数量
        checkDto.AcceptanceQty2 = container("Qty").ToString
        checkDto.ContainerName = container("ContainerName").ToString
        checkDto.ContainerID = container("ContainerID").ToString
        checkDto.WorkflowstepID = container("WorkflowstepID").ToString
        checkDto.FactoryID = m_UserInfo.FactoryID
        checkDto.CheckerID = m_UserInfo.EmployeeID
        checkDto.CheckNote = ""
        checkDto.ReportType = Val(container("CheckType").ToString) '报工类型
        checkDto.ContainerStepWorkReportID = container("ContainerStepWorkReportID").ToString
        checkDto.FirstCheckContainerNo = checkBusiness.GetFirstCheckContainerNo(container("ContainerID").ToString(), container("WorkflowstepID").ToString()) '首检批次号
        checkDto.FirstCheckBillNo = GetFirstCheckBillNo()
        checkDto.SpecimenLossQty = 0 '需开废票试件数
        checkData.Add(checkDto)
        '保存检验记录
        result = checkBusiness.SaveBatchCheckInfo(checkData, para)
        If Not result.Result Then
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        Dim containerQty As DataTable = checkBusiness.GetAllAcceptQtyList(container("ContainerID").ToString())
        Dim wipQty As Integer = 0
        If Convert.IsDBNull(containerQty.Rows(0)("QTY")) = False Then
            wipQty = Convert.ToInt64(containerQty.Rows(0)("QTY"))
        End If
        Dim accepttanceQty As Integer = 0
        If Convert.IsDBNull(containerQty.Rows(0)("ACCEPTANCEQTY")) = False Then
            accepttanceQty = Convert.ToInt64(containerQty.Compute("SUM(ACCEPTANCEQTY)", String.Empty))
        End If
        Dim lossQty As Integer = 0
        lossQty = Convert.ToInt64(containerQty.Compute("SUM(LOSSQTY)", String.Empty))
        If lossQty > 0 Then
            Dim updatePara As New Dictionary(Of String, String)
            Dim conditionPara As New Dictionary(Of String, String)
            conditionPara("ContainerID") = String.Format("'{0}'", container("ContainerID").ToString())
            updatePara("alllossqty") = lossQty
            m_ConCurrentinfo.UpdateContainerCurrentInfoByField(updatePara, conditionPara)
        End If
        '检查总表stepcheckNum,firstCheckNum
        Dim strUpdateinfo As String = ""
        strUpdateinfo = m_ConCurrentinfo.UpdateContainerCurrentinfoCheckInfo(container("ContainerID").ToString(), container("WorkflowStepID").ToString())
        'LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + row.Cells.FromKey("ContainerID").Text + "@^" + "工序：" + row.Cells.FromKey("WorkflowStepID").Text + strUpdateinfo + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName) '写入数据库   

        '检验总数为0
        If accepttanceQty = 0 Then
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If
        
        '如果检验的不是当前工序，则不需要移动
        If container("WorkflowStepID").ToString <> container("CurrWorkflowstepID").ToString Then
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        End If

        '首检 不需要移到下一序 
        If container("CheckType").ToString() = "1" And container("WIPQTY").ToString() <> "1" Then
            context.Response.Write(JsonConvert.SerializeObject(result))
            Exit Sub
        Else
            If wipQty > accepttanceQty Then '合格数小于在制数没做完
                context.Response.Write(JsonConvert.SerializeObject(result))
                Exit Sub
            End If
        End If
        '移动工序
        msg = ""
        checkBusiness.MoveNextStep(New Dictionary(Of String, String) From {{"ContainerID", container("ContainerID").ToString},
                                                                                  {"WorkflowStepID", container("WorkFlowStepID").ToString},
                                                                                   {"WorkflowID", container("WorkflowID").ToString},
                                                                                  {"Sequence", container("Sequence").ToString},
                                                                                  {"ContainerName", container("ContainerName").ToString}
                                                                                 }, host, accepttanceQty, levelAttributes, m_UserInfo, msg)
        'If MoveNextStep(container, msg, accepttanceQty) = False Then
        '    result.Result = False
        '    result.Message = "工序移动失败：" + msg
        'End If
        context.Response.Write(JsonConvert.SerializeObject(result))
    End Sub
    
    ''' <summary>
    ''' 工序移动
    ''' </summary>
    ''' <param name="row"></param>
    ''' <param name="strMsg"></param>
    ''' <param name="LastWipQty"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function MoveNextStep(ByVal row As DataRow, ByRef strMsg As String, ByVal LastWipQty As Integer) As Boolean
        MoveNextStep = False
        Dim stepid As String = row("WorkFlowStepID")
        '判断检验的当前工序是否是转工的最后一道工序 create：Wangjh 2017-6-17
        Dim isShipPara As New Dictionary(Of String, String)
        isShipPara("ToFactoryID") = m_UserInfo.FactoryID
        isShipPara("ContainerID") = row("ContainerID")
        isShipPara("WorkFlowStepID") = stepid
        Dim IsLastShipStep As Boolean = checkBusiness.IsLastShipStep(isShipPara)
        If IsLastShipStep = True Then
            MoveNextStep = True
            Exit Function
        End If

        '判断若下序是空子工艺则直接跳出 add:Wangjh 20171206
        Dim nextPara As Dictionary(Of String, String) = New Dictionary(Of String, String)
        nextPara("WorkFlowID") = row("WorkflowID")
        nextPara("Sequence") = Val(row("Sequence")) + 1
        nextPara("ContainerID") = row("ContainerID")
        nextPara("FactoryID") = m_UserInfo.FactoryID

        '获取后面第一个未完工的序 add:Wangjh 20180830
        Dim noComStep = m_Common.GetContainerNoCompleteStep(nextPara)
        If isShipPara.ContainsKey("Out_ShipLastSequence") Then '处于转工流程，并需要移动的情况 add:wangjh 20220624
            If Val(noComStep.Rows(0)("Sequence")) > Val(isShipPara("Out_ShipLastSequence")) Then '系统转移的下序>转工最后一序情况

                Dim exuteEntity = New ExcuteEntity("workflowstep", ExcuteEntity.ExcuteTypeEnum.select_)
                exuteEntity.WhereFileds = New List(Of FieldEntity) From {New FieldEntity("workflowstepid", isShipPara("Out_ShipLastStepID"), FieldEntity.FieldTypeEnum.Str)}

                exuteEntity.ExcuteFileds = New List(Of FieldEntity) From {New FieldEntity("workflowstepname", Nothing, FieldEntity.FieldTypeEnum.Str),
                                                                          New FieldEntity("sequence", Nothing, FieldEntity.FieldTypeEnum.Str),
                                                                          New FieldEntity("workflowstepid", Nothing, FieldEntity.FieldTypeEnum.Str),
                                                                          New FieldEntity("controlcode", Nothing, FieldEntity.FieldTypeEnum.Str),
                                                                          New FieldEntity("wipmsglabel", Nothing, FieldEntity.FieldTypeEnum.Str)}

                Dim lastShipDt = DatabaseHelper.QueryDataByEntity(exuteEntity)

                If lastShipDt.Rows.Count > 0 Then
                    noComStep.Rows(0)("workflowstepname") = lastShipDt.Rows(0)("workflowstepname")
                    noComStep.Rows(0)("workflowstepid") = lastShipDt.Rows(0)("workflowstepid")
                    noComStep.Rows(0)("sequence") = lastShipDt.Rows(0)("sequence")
                    noComStep.Rows(0)("controlcode") = lastShipDt.Rows(0)("controlcode")
                    noComStep.Rows(0)("wipmsglabel") = lastShipDt.Rows(0)("wipmsglabel")
                    noComStep.AcceptChanges()
                End If

            End If
        End If

        Dim host As New ServerHostInfo
        host.UserName = m_UserInfo.APIUserName
        host.Password = m_UserInfo.APIPassword
        Dim excResult = False
        Dim levelAttributes As DataTable = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID)
        Dim datarows() As DataRow = levelAttributes.Select("USERATTRIBUTENAME='入库流程'")
        Dim strWF As String = ""
        Dim strWFRev As String = ""
        If datarows.Length > 0 Then
            Dim strWorkflows() = datarows(0)("ATTRIBUTEVALUE").ToString.Split("：")
            strWF = strWorkflows.First
            strWFRev = strWorkflows.Last
        End If

        datarows = levelAttributes.Select("USERATTRIBUTENAME='入库工序'")
        Dim strStep As String = ""
        If datarows.Length > 0 Then
            strStep = datarows.First.Item("ATTRIBUTEVALUE")
        End If

        MoveContainer(row("ContainerName"), noComStep, excResult, host, strWF, strWFRev, strStep, LastWipQty, strMsg)
        LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + row("ContainerName") + "@^" + "工序：" + row("WorkFlowStepID") + strMsg + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName) 'add:Wangjh 写入数据库   
        If excResult = False Then
            Exit Function
        End If

        If noComStep.Rows.Count = 0 Then '干完入库情况，将当前批次的工艺保存下来 add by zhangrj 20220705
            m_ContainerObj.UpdateContainerBsWorkflow(row("ContainerID"), row("WorkflowID"))
        Else
            Dim dic As New Dictionary(Of String, String)
            dic.Add("ContainerID", row("ContainerID"))
            dic.Add("ContainerName", row("ContainerName"))
            dic.Add("ProductId", "")
            dic.Add("ProductName", "")
            dic.Add("EmployeeID", m_UserInfo.EmployeeID.ToString)
            dic.Add("WorkflowStepID", noComStep.Rows(0)("workflowstepid").ToString)
            dic.Add("Qty", "")
            m_ContainerObj.UpdateParallelStepContainerHold(dic) '是否平行作业工序暂停 add by zhangrj 20220808
            'm_ContainerObj.UpdateSpecialStepContainerHold(dic) '是否特殊过程工序暂停 add by zhangrj 20220908
        End If

        '若当前卡为子卡，检查主卡当前序对应的子工艺序是否全部干完，若全部干完则自动移动 add:Wangjh 20181205
        If row("ContainerName").Contains("子工艺") Or m_Common.GetTableInfo("containersubcontainer", "subcontainerid", row("ContainerID")).Rows.Count > 0 Then
            If noComStep.Rows.Count = 0 Then '增加判断-干完了入库情况，检查是否需要父卡联动 add:Wangjh 20220420
                '检查子卡所有序是否已干完
                Dim checkPara As New Dictionary(Of String, String)
                checkPara.Add("WorkflowStepID", stepid)
                checkPara.Add("ContainerID", row("ContainerID"))
                nextPara.Clear()
                Dim resMsg As String = ""
                nextPara = m_Common.CheckFaContainerAndReturnMoveInfo(checkPara, resMsg)
                If Not String.IsNullOrWhiteSpace(resMsg) Then
                    LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + row("ContainerName") + "检查主卡移动" + "@^" + resMsg + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName) 'add:Wangjh 写入数据库   
                End If
                If nextPara IsNot Nothing Then
                    noComStep = m_Common.GetContainerNoCompleteStep(nextPara)
                    MoveContainer(nextPara("ContainerName"), noComStep, excResult, host, strWF, strWFRev, strStep, Val(nextPara("WipQty")), strMsg)
                    LogHelp.WriteOrcale("检验日志记录" + "@^" + "批次：" + row("ContainerName") + "检查主卡移动" + "@^" + "主卡:" + nextPara("ContainerName") + strMsg + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName) 'add:Wangjh 写入数据库   
                End If
                '
            End If


        End If
        '
        MoveNextStep = True
    End Function
    
    ''' <summary>
    ''' 移动批次
    ''' add:Wangjh 20181205
    ''' </summary>
    ''' <param name="noComStep"></param>
    ''' <param name="excResult"></param>
    ''' <param name="host"></param>
    ''' <param name="strWF"></param>
    ''' <param name="strWFRev"></param>
    ''' <param name="strStep"></param>
    ''' <param name="LastWipQty"></param>
    ''' <param name="strMsg"></param>
    ''' <remarks></remarks>
    Sub MoveContainer(ByVal containerName As String, ByVal noComStep As DataTable, ByRef excResult As Boolean, ByVal host As ServerHostInfo, ByVal strWF As String, ByVal strWFRev As String, ByVal strStep As String, ByVal LastWipQty As Integer, ByRef strMsg As String)

        If noComStep.Rows.Count = 0 Then
            excResult = m_ContainerObj.ContainerMoveNonStd(host, containerName, strWF, strWFRev, strStep, m_UserInfo.EmployeeName, "", strMsg)
        Else
            '非标移动到转工最后序后面第一个未完工的序
            excResult = m_ContainerObj.ContainerMoveNonStd(host, noComStep.Rows(0)("ContainerName").ToString, noComStep.Rows(0)("WORKFLOWNAME").ToString, noComStep.Rows(0)("WORKFLOWREVISION").ToString, noComStep.Rows(0)("workflowstepname").ToString, m_UserInfo.EmployeeName, noComStep.Rows(0)("workflowstepID").ToString, strMsg)
            If noComStep.Rows(0)("controlcode").ToString = "LY05" Then '固定外委
                'If m_CommonObj.GetControlCodeByWorkflowStepID(noComStep.Rows(0)("WORKFLOWSTEPID")) = "LY05" Then '固定外委
                Dim newpara As New Dictionary(Of String, String)
                newpara.Add("WorkflowID", noComStep.Rows(0)("WorkflowID").ToString)
                newpara.Add("Sequence", noComStep.Rows(0)("Sequence").ToString)
                newpara.Add("WorkflowStepID", noComStep.Rows(0)("WorkflowStepID").ToString)
                newpara.Add("FactoryID", m_UserInfo.FactoryID)
                newpara.Add("EmployeeID", m_UserInfo.EmployeeID)
                newpara.Add("OutQty", LastWipQty)
                newpara.Add("ContainerID", noComStep.Rows(0)("ContainerID").ToString)
                newpara.Add("ContainerName", noComStep.Rows(0)("ContainerName").ToString)
                m_Commission.AddFixedCommissionInfo(newpara)
            End If
        End If

    End Sub
    
    ''' <summary>
    ''' 获取首件检验单号
    ''' </summary>
    ''' <remarks></remarks>
    Private Function GetFirstCheckBillNo() As String
        '获取首件检验单号，车间唯一
        Dim strFactoryCode As String = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "分厂代码")
        strFactoryCode = String.Format("{0}首-{1}", Date.Now.Year, strFactoryCode)
        strFactoryCode = checkBusiness.GetFirstCheckBillNo(strFactoryCode)
        Return strFactoryCode
    End Function
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class